package logic;

import java.awt.geom.Rectangle2D;
import java.util.Vector;

import vis.GLine;
import vis.GPoint;

public class Polygon {
	protected Vector<GPoint> pts = new Vector<GPoint>();
	protected Vector<GLine> edges = new Vector<GLine>();
	protected GLine closure = null;
	
	public Polygon() {
		
	}
	
	public void addPoint(GPoint p)
	{
		if(!pts.contains(p))
		{
			pts.add(p);
			if(pts.size() >= 2)
			{
				edges.add(new GLine(pts.get(pts.size() - 2), p));
				edges.lastElement().setParent(this);
			}
			if(pts.size() >= 3 || closure == null)
			{
				closure = new GLine(pts.lastElement(), pts.firstElement());
				closure.setParent(this);
			}
			else
			{
				closure.p[0] = pts.lastElement();
			}
		}
	}
	
	public void translate(double x, double y)
	{
		for(PointD p : pts)
		{
			p.X += x;
			p.Y += y;
		}
	}
	
	public void clear()
	{
		pts.clear();
		edges.clear();
		closure = null;
	}
	
	public Rectangle2D getBoundingRect()
	{
		if(pts.size() < 3) return null;
		double minX = pts.firstElement().getX();
		double minY = pts.firstElement().getY();
		double maxX = pts.firstElement().getX();
		double maxY = pts.firstElement().getY();
		
		for(PointD p : pts)
		{
			if(p.getX() > maxX) maxX = p.getX();
			if(p.getY() > maxY) maxY = p.getY();
			if(p.getX() < maxX) maxX = p.getX();
			if(p.getY() < maxY) maxY = p.getY();
		}
		
		return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY);
	}
	
	public Vector<GLine> convertReferences(Vector<GLine> lines)
	{
		Vector<GLine> list = new Vector<GLine>();
		for(GLine line : lines)
		{
			for(GLine edge : edges)
			{
				if(line.equals(edge))
				{
					edge.meta1 = line.meta1;
					edge.meta2 = line.meta2;
					edge.meta3 = line.meta3;
					edge.makeRight();
					edge.setParent(this);
					list.add(edge);
					break;
				}
			}
			if(closure != null)
				if(closure.equals(line))
				{
					closure.meta1 = line.meta1;
					closure.meta2 = line.meta2;
					closure.meta3 = line.meta3;
					closure.makeRight();
					closure.setParent(this);
					list.add(closure);
				}
		}
		System.out.println("Delta : " + (lines.size() - list.size()));
		return list;
	}
	
	public int getVertexCount()
	{
		return pts.size();
	}
}
